// export default {
//     data () {
//         return {
//             remoteDataLoading: 0,
//         }
//     }
// }
// 使用
// mixins: [
//     RemoteData
// ],
//
//mixin 一般我们使用下面这种写法, 可以传参
export default function (resources) {
    return {
        data () {
           let initData = {
               remoteDataLoading:0,
           }

           //初始化数据
           for (const key in resources){
               initData[key] = null
           }
           initData.remoteErrors = {}
           for (const key in resources){
               initData[key] = null
               initData.remoteErrors[key] = null
           }

           return initData
        },
        methods: {
            async fetchResource (key, url) {
                this.$data.remoteDataLoading++
                //重置错误
                this.$data.remoteErrors[key] = null
                try {
                    this.$data[key] = await this.$fetch(url)
                } catch (e) {
                    console.log(e)
                    this.$data.remoteErrors[key] = e
                }
                this.$data.remoteDataLoading--
            }
        },
        created(){
            for (const key in resources) {
                let url = resources[key]
                if(typeof url === 'function'){
                    this.$watch(url, (val)=>{
                        this.fetchResource(key, val)
                    }, {
                        immediate: true,
                    } )
                } else {

                    this.fetchResource(key, url)
                }
            }
        },
        computed: {
            remoteDataBusy(){
                return this.$data.remoteDataLoading !== 0
            },
            hasRemoteErrors(){
                return Object.keys(this.$data.remoteErrors).some(key => this.$data.remoteErrors[key])
            }
        },
    }
}